<?php
class User
{
	public function construct()
	{
		
	}
	
	public function index()
	{
		/*CommonFunc::loadFile(ADAPTOR . "Login.php");
		$loginhelper = new LoginHelper();
		$loginhelper->login("addtocart");*/
	}	
	public function ActivateUser()
        {
            	CommonFunc::loadFile("model/User.php");
                CommonFunc::loadFile(ADAPTOR . "Encryption.php");
                
                $modUser = new FrontUser();
		$expression = CommonFunc::getRequestGET();
                $arr = explode('/', $_SERVER['QUERY_STRING']);
                //print_r($arr);
                $noitem = sizeof($arr,0);

                $noitem = $noitem - 1;
               // echo $noitem;
                $encryptserid = $arr[$noitem];
                $encryption = new Encryption();
                //echo $encryptserid;
                $userid = $encryption->decode($encryptserid);
               
		$modUser ->useractivate($userid);



        }
	public function doLogin()
	{
		CommonFunc::loadFile("model/User.php");
		$modUser = new FrontUser();
		$request = CommonFunc::getRequest();
		$email = $request['email'];
		$password = md5($request['password']);
		//$lang = $_SESSION['lang'];
		$user_arr = $modUser->validateUser($email, $password);
	}
	
	public function createUser()
	{
		CommonFunc::loadFile("model/User.php");
		$modUser = new FrontUser();
		//$country_arr = $modUser->getCountries();
		include SITETPL . "user/register.phtml";	
	}

        public function editprofile()
	{
               if(empty($_SESSION["user_id"])){
                   header("Location: index.php");
               }
		CommonFunc::loadFile("model/User.php");
		$modUser = new FrontUser();
		$user_arr = $modUser->getUserdetails();
                $options=array();
                $options=array(0=>array('val'=>0,'dsc'=>"hide"),1=>array('val'=>1,'dsc'=>"show"));
		include SITETPL . "user/editprofile.phtml";
	}

        public function doCreateUser()
	{

            CommonFunc::loadFile(ADAPTOR . "securimage.php");
             $img = new Securimage();
             $valid = $img->check($_POST['image_code']);

        if($valid == FALSE) {
          $validation_error['image_code'] = "<li class='error'>Sorry, the code you entered was invalid</li>";
        }
 else {
    


            //echo "user controller ok      ";
		CommonFunc::loadFile("model/User.php");
                CommonFunc::loadFile(ADAPTOR . "Mail.php");
		$modUser = new FrontUser();
		$request = CommonFunc::getRequest();
               
		$addusersuc=$modUser->addUser($request);
                $userid=DB::lastInsertID();
                //echo $addusersuc;
        if($addusersuc=="suc"){
             $this->sendregmailadmin($request,$userid);
             $this->sendregmailuser($request,$userid);

	   echo "<span class='success'>You are successfully registered. Please check your mail box to activate your account</span>";

         }
         else if($addusersuc=="uex"){
            echo "<span class='error'>User email already exist in the database</span>";
	     include SITETPL . "user/register.phtml";
         }
         else{
             echo "<span class='error'>Register failed ! Please try again!</span>";
         }
         }

	}
        public function login()
	{
		CommonFunc::loadFile("model/User.php");
		$modUser = new FrontUser();

		include SITETPL . "user/login.phtml";
	}
	
	public function doeditprofile()
	{
		CommonFunc::loadFile("model/User.php");
		$modUser = new FrontUser();
		$request = CommonFunc::getRequest();
		$addusersuc=$modUser->editprofilefront($request);
                header("Location: index.php/?editprofile");
	}

      public function sendregmailuser($request,$userid)
	{
               // echo 'ok fond';

         // CommonFunc::loadFile(SMARTYLIBS . "Smarty.class.php");
		CommonFunc::loadFile(ADAPTOR . "Encryption.php");
                
                $encrypt = new Encryption();
                
                $value = $userid;
                $encryptid = $encrypt->encode($value);
   
                //echo $encryptid;
                $name = $request['user_firstname'];
		$email = $request['user_email'];
		$tel = $request['user_phone'];
		//$message = $request['msg'];
                $subject="Your are registered at " . SITENAME;
		$msgbody = "";

		

		$msgbody .= "Dear " . $name .",<br>\n\n";
		$msgbody .= "Thank you for joining lankanpets. Please click on the  following link to activate your account<br>";
                $msgbody .= "http://www.lankanpets.com/index.php/?activateuser/user_id/".$encryptid."\n\n<br>";

		$msgbody .= "----------------------------------------------\n\n<br>";
		$msgbody .= "<br>Name: " . $name . "\n\n<br>" . "<br>Email: " . $email . "<br>\n\n<br>" ;
		$msgbody .= "<br>----------------------------------------------<br>\n\n<br>";
		$msgbody .= "<br>This is an auto generated email. Please do not reply<br>";
        // echo $msgbody;
       // exit;
        $mail = new PHPMailer();
		$mail->IsMail();
		$mail->IsHTML(true);
                $mail->FromName = 'Sri Lanka Pets';
                $mail->From = 'info@lankanpets.com';
		$mail->AddAddress($email);

                $mail->AddCC('info@lankanpets.com');
                $mail->AddBCC($email);
                $mail->AddReplyTo('info@lankanpets.com');
		$mail->Subject = $subject;
		$mail->Body = $msgbody;
		
		if(!$mail->Send())
		{
		   echo "Error sending: " . $mail->ErrorInfo;;
		}
                else{
                    $mail->ClearAddresses();
                    $mail->ClearAttachments();
                }

		
	}

       public function sendregmailadmin($form_values,$userid)
    {
	    $subject="A new user  registered at " . SITENAME;
		$message="
		   <p> Hello {$form_values['user_firstname']} ,</p>
		   <p>  A new user successfully registered at " . SITENAME . "
		   Your Details are as below.</p>
		   <p>First Name : {$form_values['user_firstname']}</p>
		   <p>Last Name  : {$form_values['user_lastname']}</p>
		   <p>Email      : {$form_values['user_email']}</p>
		   <p>Address    : {$form_values['user_address']}</p>
		  
		   <p>Telephone  : {$form_values['user_phone']}</p>
                   <p> Best Regards!</p>
		   <p> info@lankanpets.com.</p>";
		//print_r($message);
                //exit;
		$sender_email = $form_values['user_email'];
		//echo $message;
                //exit;
		$mail = new PHPMailer();
		$mail->IsMail();
		$mail->IsHTML(true);
                $mail->FromName = 'Lanka Pets';
                $mail->From = 'info@lankanpets.com';
		$mail->AddAddress($sender_email);
                
                $mail->AddCC($sender_email);
		$mail->Subject = $subject;
		$mail->Body = $message;
               
		if(!$mail->Send())
		{
		   echo "Error sending: " . $mail->ErrorInfo;;
		}
                else{
                    $mail->ClearAddresses();
                    $mail->ClearAttachments();
                }
    }

    public function checkuserexist() 
	{
                CommonFunc::loadFile("model/User.php");
		$request = CommonFunc::getRequest();
                $modUser = new FrontUser();
                $userexist=$modUser->isEmailexist($request["email"]);
               // print_r($userexist);
                if($userexist){
                       include SITETPL . "user/forgotpasswordstep2.phtml";

                 }
                 else{
                      echo "Invalid Email!";
                       include SITETPL . "user/forgotpasswordstep1.phtml";
                 }
	 
	}

        	public function forgotpassstep2()
	{
                CommonFunc::loadFile("model/User.php");
		$request = CommonFunc::getRequest();
                $modUser = new FrontUser();
                $answercorrect=$modUser->isAnswerCorrect($request["userid"],$request["securityanswer"] );
              // print_r($answercorrect);
                if($answercorrect){
                      $newpassword=$this->generaterandompassword();
                      $modUser->updatepass($request["userid"],$newpassword);
                      $this->sendpasswordmail($answercorrect[0]["user_email"],$newpassword);
		      

                 }
                 else{
                       $userinfo=$modUser-> getUserInfoById2($request["userid"]);
                       $userexist[0]["secret_question"]=$userinfo["secret_question"];
                       $userexist[0]["user_id"]=$userinfo["user_id"];
                       //print_r($userexist);
                       // echo $request["userid"];
                       echo "Incorrect Answer!";
                       include SITETPL . "user/forgotpasswordstep2.phtml";
                 }

	}

	public function sendpasswordmail($email,$newpassword)
	{
                CommonFunc::loadFile(ADAPTOR . "Mail.php");
		$message="";
                $subject="Password Reminder at Officesupplies.lk ";
                $message="
		<p style=\"font-family: verdana; font-size: 11px;\">Dear User,</p>

		<p style=\"font-family: verdana; font-size: 11px;\">Herewith we are sending you a new password for officesupplies.lk as you requested.</p>
		<p style=\"font-family: verdana; font-size: 11px;\">Email: {$email}</p>
		<p style=\"font-family: verdana; font-size: 11px;\">New Password: <b>{$newpassword}</b></p>
		<p>&nbsp;</p>
		<p style=\"font-family: verdana; font-size: 11px;\"> Best Regards!</p>
		<p style=\"font-family: verdana; font-size: 11px;\"> Officesupplies.lk.</p>";
                //echo $message;
		$mail = new PHPMailer();
		$mail->IsMail();
		$mail->IsHTML(true);
		$mail->AddAddress($email);
		$mail->Subject = $subject;
		$mail->Body = $message;
//echo $message;exit;
		
		if(!$mail->Send())
		{
			   echo "Error sending: " . $mail->ErrorInfo;;
		}
		else
		{
			  echo "Your password Sent to your email. Please check your mail box";
		}
			

	}
        private  function generaterandompassword ($length = 8)
		  {

		    // start with a blank password
		    $password = "";

		    // define possible characters - any character in this string can be
		    // picked for use in the password, so if you want to put vowels back in
		    // or add special characters such as exclamation marks, this is where
		    // you should do it
		    $possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";

		    // we refer to the length of $possible a few times, so let's grab it now
		    $maxlength = strlen($possible);

		    // check for length overflow and truncate if necessary
		    if ($length > $maxlength) {
		      $length = $maxlength;
		    }

		    // set up a counter for how many characters are in the password so far
		    $i = 0;

		    // add random characters to $password until $length is reached
		    while ($i < $length) {

		      // pick a random character from the possible ones
		      $char = substr($possible, mt_rand(0, $maxlength-1), 1);

		      // have we already used this character in $password?
		      if (!strstr($password, $char)) {
		        // no, so it's OK to add it onto the end of whatever we've already got...
		        $password .= $char;
		        // ... and increase the counter by one
		        $i++;
		      }

		    }

		    // done!
		    return $password;

		  }
}

?>